//
//  JSBundleModel.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/3/4.
//

import Fluent
import Vapor

final class JSBundleModel: Model, Content {
    static let schema = "js_bundles"
    
    @ID(custom: FieldKeys.id)
    var id: String?
    
    @Field(key: FieldKeys.appVersion)
    var appVersion: String
    
    @Field(key: FieldKeys.jsVersion)
    var jsVersion: String
    
    @Field(key: FieldKeys.downloadUrl)
    var downloadUrl: String
    
    @Field(key: FieldKeys.md5)
    var md5: String
    
    @Timestamp(key: FieldKeys.uploadDate, on: .create)
    var uploadDate: Date?
    
    init() {}
    
    init(id: String?, appVersion: String, jsVersion: String, downloadUrl: String, md5: String) {
        self.id = id
        self.appVersion = appVersion
        self.jsVersion = jsVersion
        self.downloadUrl = downloadUrl
        self.md5 = md5
    }
}

extension JSBundleModel {
    struct FieldKeys {
        static var id: FieldKey { "app_id" }
        static var appVersion: FieldKey { "app_version" }
        static var jsVersion: FieldKey { "js_version" }
        static var downloadUrl: FieldKey { "download_url" }
        static var md5: FieldKey { "md5" }
        static var uploadDate: FieldKey { "upload_date" }
    }
}

struct JSBundleModelMigration: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema(JSBundleModel.schema)
            .field(JSBundleModel.FieldKeys.id, .string, .required ,.custom("COMMENT '记录ID'"))
            .field(JSBundleModel.FieldKeys.appVersion, .string, .required, .custom("COMMENT 'APP版本号'"))
            .field(JSBundleModel.FieldKeys.jsVersion, .string, .required, .custom("COMMENT 'JS版本号'"))
            .field(JSBundleModel.FieldKeys.downloadUrl, .string, .required, .custom("COMMENT 'JS包下载地址'"))
            .field(JSBundleModel.FieldKeys.md5, .string, .required, .custom("COMMENT 'JS包MD5值'"))
            .field(JSBundleModel.FieldKeys.uploadDate, .datetime, .required, .custom("COMMENT '上传时间'"))
            .unique(on: JSBundleModel.FieldKeys.appVersion, JSBundleModel.FieldKeys.jsVersion)
            .create()
    }
    
    func revert(on database: Database) async throws {
        try await database.schema(JSBundleModel.schema).delete()
    }
}

